//
//  FCCImagePreviewViewController.swift
//  chatUIDemo
//
//  Created by admin on 2025/7/10.
//

import UIKit
import SnapKit

class FCCImagePreviewViewController: UIViewController {
    
    // MARK: - UI组件
    private let qfcScrollView = UIScrollView()
    private let qfcImageView = UIImageView()
    private let qfcCloseButton = UIButton()
    private let qfcSaveButton = UIButton()
    private let qfcShareButton = UIButton()
    private let qfcToolbar = UIView()
    private let qfcPageControl = UIPageControl()
    private let qfcBackgroundView = UIVisualEffectView(effect: nil)
    private let qfcLoadingIndicator = UIActivityIndicatorView(style: .large)
    
    // MARK: - 数据
    private let qfcImage: UIImage
    private var qfcIsToolbarHidden = false
    private var qfcImages: [UIImage]? = nil
    private var qfcCurrentIndex: Int = 0
    
    // MARK: - 转场动画相关
    private var qfcSourceView: UIView? = nil
    private var qfcSourceFrame: CGRect? = nil
    private var qfcInteractiveDismiss = false
    private var qfcDismissalInteractionInProgress = false
    
    // MARK: - 初始化
    init(qfcImage: UIImage) {
        self.qfcImage = qfcImage
        super.init(nibName: nil, bundle: nil)
        modalPresentationStyle = .fullScreen
        modalTransitionStyle = .crossDissolve
    }
    
    // 支持多图片预览的初始化方法
    init(qfcImages: [UIImage], qfcCurrentIndex: Int = 0) {
        self.qfcImage = qfcImages[qfcCurrentIndex]
        self.qfcImages = qfcImages
        self.qfcCurrentIndex = qfcCurrentIndex
        super.init(nibName: nil, bundle: nil)
        modalPresentationStyle = .fullScreen
        modalTransitionStyle = .crossDissolve
    }
    
    // 支持转场动画的初始化方法
    init(qfcImage: UIImage, qfcSourceView: UIView, qfcSourceFrame: CGRect) {
        self.qfcImage = qfcImage
        self.qfcSourceView = qfcSourceView
        self.qfcSourceFrame = qfcSourceFrame
        super.init(nibName: nil, bundle: nil)
        modalPresentationStyle = .overFullScreen
        modalTransitionStyle = .crossDissolve
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        qfcSetupUI()
        qfcSetupGestures()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        // 如果有源视图，执行自定义转场动画
        if let sourceFrame = qfcSourceFrame {
            qfcPerformPresentAnimation(fromFrame: sourceFrame)
        }
    }
    
    override var prefersStatusBarHidden: Bool {
        return true
    }
    
    // MARK: - UI设置
    private func qfcSetupUI() {
        view.backgroundColor = .clear
        
        // 背景模糊视图设置
        qfcBackgroundView.frame = view.bounds
        qfcBackgroundView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        view.addSubview(qfcBackgroundView)
        
        // 滚动视图设置
        qfcScrollView.delegate = self
        qfcScrollView.minimumZoomScale = 1.0
        qfcScrollView.maximumZoomScale = 3.0
        qfcScrollView.showsVerticalScrollIndicator = false
        qfcScrollView.showsHorizontalScrollIndicator = false
        qfcScrollView.bounces = true
        qfcScrollView.bouncesZoom = true
        qfcScrollView.decelerationRate = .fast
        view.addSubview(qfcScrollView)
        
        // 图片视图设置
        qfcImageView.contentMode = .scaleAspectFit
        qfcImageView.image = qfcImage
        qfcImageView.clipsToBounds = true
        // 添加阴影效果
        qfcImageView.layer.shadowColor = UIColor.black.cgColor
        qfcImageView.layer.shadowOffset = CGSize(width: 0, height: 2)
        qfcImageView.layer.shadowOpacity = 0.3
        qfcImageView.layer.shadowRadius = 3.0
        qfcScrollView.addSubview(qfcImageView)
        
        // 加载指示器设置
        qfcLoadingIndicator.hidesWhenStopped = true
        qfcLoadingIndicator.color = .white
        qfcLoadingIndicator.center = view.center
        view.addSubview(qfcLoadingIndicator)
        
        // 工具栏设置
        qfcToolbar.backgroundColor = UIColor.black.withAlphaComponent(0.7)
        view.addSubview(qfcToolbar)
        
        // 关闭按钮设置
        qfcCloseButton.setImage(UIImage(systemName: "xmark"), for: .normal)
        qfcCloseButton.tintColor = .white
        qfcCloseButton.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        qfcCloseButton.layer.cornerRadius = 20
        qfcCloseButton.addTarget(self, action: #selector(qfcCloseButtonTapped), for: .touchUpInside)
        view.addSubview(qfcCloseButton)
        
        // 保存按钮设置
        qfcSaveButton.setImage(UIImage(systemName: "square.and.arrow.down"), for: .normal)
        qfcSaveButton.tintColor = .white
        qfcSaveButton.addTarget(self, action: #selector(qfcSaveButtonTapped), for: .touchUpInside)
        qfcToolbar.addSubview(qfcSaveButton)
        
        // 分享按钮设置
        qfcShareButton.setImage(UIImage(systemName: "square.and.arrow.up"), for: .normal)
        qfcShareButton.tintColor = .white
        qfcShareButton.addTarget(self, action: #selector(qfcShareButtonTapped), for: .touchUpInside)
        qfcToolbar.addSubview(qfcShareButton)
        
        // 页面指示器设置（多图片预览时使用）
        if let images = qfcImages, images.count > 1 {
            qfcPageControl.numberOfPages = images.count
            qfcPageControl.currentPage = qfcCurrentIndex
            qfcPageControl.pageIndicatorTintColor = .gray
            qfcPageControl.currentPageIndicatorTintColor = .white
            qfcPageControl.isUserInteractionEnabled = false
            view.addSubview(qfcPageControl)
        }
        
        qfcSetupConstraints()
    }
    
    private func qfcSetupConstraints() {
        // 背景模糊视图约束
        qfcBackgroundView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        // 滚动视图约束
        qfcScrollView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        // 图片视图约束
        qfcImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.width.equalTo(qfcScrollView)
            make.height.equalTo(qfcScrollView)
        }
        
        // 加载指示器约束
        qfcLoadingIndicator.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
        
        // 工具栏约束
        qfcToolbar.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.height.equalTo(50)
        }
        
        // 关闭按钮约束
        qfcCloseButton.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide).offset(20)
            make.leading.equalToSuperview().offset(20)
            make.width.height.equalTo(40)
        }
        
        // 保存按钮约束
        qfcSaveButton.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.trailing.equalTo(qfcShareButton.snp.leading).offset(-30)
            make.width.height.equalTo(30)
        }
        
        // 分享按钮约束
        qfcShareButton.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.trailing.equalToSuperview().offset(-30)
            make.width.height.equalTo(30)
        }
        
        // 页面指示器约束（多图片预览时使用）
        if qfcImages != nil && qfcImages!.count > 1 {
            qfcPageControl.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
                make.bottom.equalTo(qfcToolbar.snp.top).offset(-10)
            }
        }
    }
    
    private func qfcSetupGestures() {
        // 双击缩放手势
        let qfcDoubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(qfcDoubleTapped(_:)))
        qfcDoubleTapGesture.numberOfTapsRequired = 2
        qfcScrollView.addGestureRecognizer(qfcDoubleTapGesture)
        
        // 单击切换工具栏显示状态手势
        let qfcSingleTapGesture = UITapGestureRecognizer(target: self, action: #selector(qfcSingleTapped))
        qfcSingleTapGesture.numberOfTapsRequired = 1
        qfcSingleTapGesture.require(toFail: qfcDoubleTapGesture)
        qfcScrollView.addGestureRecognizer(qfcSingleTapGesture)
        
        // 长按手势（显示更多选项）
        let qfcLongPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(qfcLongPressed(_:)))
        qfcLongPressGesture.minimumPressDuration = 0.5
        qfcScrollView.addGestureRecognizer(qfcLongPressGesture)
        
        // 添加左右滑动手势（多图片预览时使用）
        if qfcImages != nil && qfcImages!.count > 1 {
            let qfcSwipeLeftGesture = UISwipeGestureRecognizer(target: self, action: #selector(qfcSwipeLeft))
            qfcSwipeLeftGesture.direction = .left
            view.addGestureRecognizer(qfcSwipeLeftGesture)
            
            let qfcSwipeRightGesture = UISwipeGestureRecognizer(target: self, action: #selector(qfcSwipeRight))
            qfcSwipeRightGesture.direction = .right
            view.addGestureRecognizer(qfcSwipeRightGesture)
        }
        
        // 添加交互式关闭手势 - 下拉关闭
        let qfcPanGesture = UIPanGestureRecognizer(target: self, action: #selector(qfcHandlePanGesture(_:)))
        view.addGestureRecognizer(qfcPanGesture)
    }
    
    // MARK: - 交互式关闭手势处理
    @objc private func qfcHandlePanGesture(_ gesture: UIPanGestureRecognizer) {
        let translation = gesture.translation(in: view)
        let velocity = gesture.velocity(in: view)
        
        // 计算拖动进度，仅考虑垂直方向
        let progress = translation.y / view.bounds.height
        
        switch gesture.state {
        case .began:
            qfcDismissalInteractionInProgress = true
            qfcInteractiveDismiss = true
            
        case .changed:
            // 确保进度在0-1之间
            let boundedProgress = min(max(progress, 0), 1)
            
            // 根据拖动距离更新UI
            updateDismissalAnimation(progress: boundedProgress)
            
        case .ended, .cancelled:
            qfcDismissalInteractionInProgress = false
            
            // 如果速度足够快或拖动距离超过阈值，完成关闭动画
            if progress > 0.3 || velocity.y > 300 {
                finishDismissalAnimation()
            } else {
                // 否则取消关闭动画
                cancelDismissalAnimation()
            }
            
        default:
            break
        }
    }
    
    private func updateDismissalAnimation(progress: CGFloat) {
        // 更新背景透明度
        view.backgroundColor = UIColor.black.withAlphaComponent(1 - progress)
        qfcBackgroundView.effect = UIBlurEffect(style: .dark).copy() as? UIVisualEffect
        qfcBackgroundView.alpha = 1 - progress
        
        // 更新工具栏透明度
        qfcToolbar.alpha = 1 - progress
        qfcCloseButton.alpha = 1 - progress
        qfcPageControl.alpha = 1 - progress
        
        // 缩放和移动图片视图
        let scale = max(0.5, 1 - progress * 0.5)
        qfcImageView.transform = CGAffineTransform(scaleX: scale, y: scale)
            .translatedBy(x: 0, y: progress * 200) // 向下移动
    }
    
    private func finishDismissalAnimation() {
        // 如果有源视图和源框架，使用它们进行关闭动画
        if let sourceFrame = qfcSourceFrame {
            qfcPerformDismissAnimation(toFrame: sourceFrame)
        } else {
            // 否则执行标准关闭动画
            UIView.animate(withDuration: 0.25, animations: {
                self.qfcImageView.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
                    .translatedBy(x: 0, y: self.view.bounds.height)
                self.view.backgroundColor = UIColor.clear
                self.qfcBackgroundView.alpha = 0
                self.qfcToolbar.alpha = 0
                self.qfcCloseButton.alpha = 0
                self.qfcPageControl.alpha = 0
            }) { _ in
                self.dismiss(animated: false)
            }
        }
    }
    
    private func cancelDismissalAnimation() {
        // 恢复到原始状态
        UIView.animate(withDuration: 0.2, animations: {
            self.qfcImageView.transform = .identity
            self.view.backgroundColor = UIColor.black
            self.qfcBackgroundView.alpha = 1
            self.qfcToolbar.alpha = 1
            self.qfcCloseButton.alpha = 1
            self.qfcPageControl.alpha = 1
        })
    }
    
    // MARK: - 手势处理
    @objc private func qfcDoubleTapped(_ qfcGesture: UITapGestureRecognizer) {
        if qfcScrollView.zoomScale > qfcScrollView.minimumZoomScale {
            qfcScrollView.setZoomScale(qfcScrollView.minimumZoomScale, animated: true)
        } else {
            let qfcLocation = qfcGesture.location(in: qfcImageView)
            let qfcZoomRect = qfcZoomRectForScale(qfcScrollView.maximumZoomScale, center: qfcLocation)
            qfcScrollView.zoom(to: qfcZoomRect, animated: true)
        }
    }
    
    @objc private func qfcSingleTapped() {
        // 切换工具栏显示状态
        qfcIsToolbarHidden = !qfcIsToolbarHidden
        
        UIView.animate(withDuration: 0.3) {
            self.qfcToolbar.alpha = self.qfcIsToolbarHidden ? 0 : 1
            self.qfcCloseButton.alpha = self.qfcIsToolbarHidden ? 0 : 1
            self.qfcPageControl.alpha = self.qfcIsToolbarHidden ? 0 : 1
        }
    }
    
    @objc private func qfcLongPressed(_ qfcGesture: UILongPressGestureRecognizer) {
        if qfcGesture.state == .began {
            // 显示更多选项菜单
            let qfcActionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
            
            qfcActionSheet.addAction(UIAlertAction(title: "Save Image", style: .default) { _ in
            self.qfcSaveImage()
        })
        
        qfcActionSheet.addAction(UIAlertAction(title: "Share Image", style: .default) { _ in
            self.qfcShareImage()
        })
        
        qfcActionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel))
            
            // 适配iPad
            if let popoverController = qfcActionSheet.popoverPresentationController {
                popoverController.sourceView = self.view
                popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
                popoverController.permittedArrowDirections = []
            }
            
            present(qfcActionSheet, animated: true)
        }
    }
    
    @objc private func qfcSwipeLeft() {
        guard let images = qfcImages, qfcCurrentIndex < images.count - 1 else { return }
        qfcCurrentIndex += 1
        qfcUpdateCurrentImage()
    }
    
    @objc private func qfcSwipeRight() {
        guard let images = qfcImages, qfcCurrentIndex > 0 else { return }
        qfcCurrentIndex -= 1
        qfcUpdateCurrentImage()
    }
    
    private func qfcUpdateCurrentImage() {
        guard let images = qfcImages else { return }
        
        // 重置缩放比例
        qfcScrollView.zoomScale = 1.0
        
        // 更新图片
        UIView.transition(with: qfcImageView, duration: 0.3, options: .transitionCrossDissolve, animations: {
            self.qfcImageView.image = images[self.qfcCurrentIndex]
        }, completion: nil)
        
        // 更新页面指示器
        qfcPageControl.currentPage = qfcCurrentIndex
    }
    
    // MARK: - 按钮事件
    @objc private func qfcCloseButtonTapped() {
        // 如果有源视图，执行自定义转场动画
        if let sourceFrame = qfcSourceFrame {
            qfcPerformDismissAnimation(toFrame: sourceFrame)
        } else {
            dismiss(animated: true)
        }
    }
    
    @objc private func qfcSaveButtonTapped() {
        qfcSaveImage()
    }
    
    @objc private func qfcShareButtonTapped() {
        qfcShareImage()
    }
    
    // MARK: - 辅助方法
    private func qfcSaveImage() {
        UIImageWriteToSavedPhotosAlbum(qfcImages?[qfcCurrentIndex] ?? qfcImage, self, #selector(qfcImage(_:didFinishSavingWithError:contextInfo:)), nil)
    }
    
    @objc private func qfcImage(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
        if let error = error {
            // Save failed
             let qfcAlert = UIAlertController(title: "Save Failed", message: error.localizedDescription, preferredStyle: .alert)
             qfcAlert.addAction(UIAlertAction(title: "OK", style: .default))
             present(qfcAlert, animated: true)
         } else {
             // Save successful
            let qfcAlert = UIAlertController(title: "Save Successful", message: "Image has been saved to Photos", preferredStyle: .alert)
            qfcAlert.addAction(UIAlertAction(title: "OK", style: .default))
            present(qfcAlert, animated: true)
        }
    }
    
    private func qfcShareImage() {
        let qfcImage = qfcImages?[qfcCurrentIndex] ?? self.qfcImage
        let qfcActivityViewController = UIActivityViewController(activityItems: [qfcImage], applicationActivities: nil)
        
        // 适配iPad
        if let popoverController = qfcActivityViewController.popoverPresentationController {
            popoverController.sourceView = qfcShareButton
            popoverController.sourceRect = qfcShareButton.bounds
        }
        
        present(qfcActivityViewController, animated: true)
    }
    
    // MARK: - 缩放辅助方法
    private func qfcZoomRectForScale(_ qfcScale: CGFloat, center: CGPoint) -> CGRect {
        var qfcZoomRect = CGRect.zero
        qfcZoomRect.size.height = qfcImageView.frame.size.height / qfcScale
        qfcZoomRect.size.width = qfcImageView.frame.size.width / qfcScale
        qfcZoomRect.origin.x = center.x - (qfcZoomRect.size.width / 2.0)
        qfcZoomRect.origin.y = center.y - (qfcZoomRect.size.height / 2.0)
        return qfcZoomRect
    }
    
    // MARK: - 转场动画
    private func qfcPerformPresentAnimation(fromFrame: CGRect) {
        // 显示加载指示器
        qfcLoadingIndicator.startAnimating()
        
        // 初始状态设置
        qfcToolbar.alpha = 0
        qfcCloseButton.alpha = 0
        qfcPageControl.alpha = 0
        qfcBackgroundView.alpha = 0
        qfcBackgroundView.effect = nil
        view.backgroundColor = UIColor.clear  // 从透明开始
        
        // 设置初始frame
        qfcImageView.frame = fromFrame
        qfcImageView.contentMode = .scaleAspectFill
        qfcImageView.clipsToBounds = true
        
        // 使用弹簧动画效果，使动画更自然
        UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, options: [], animations: {
            self.view.backgroundColor = UIColor.black.withAlphaComponent(0.9)
            self.qfcBackgroundView.effect = UIBlurEffect(style: .dark)
            self.qfcBackgroundView.alpha = 1.0
            self.qfcImageView.frame = self.qfcScrollView.bounds
            self.qfcImageView.contentMode = .scaleAspectFit
        }) { _ in
            // 停止加载指示器
            self.qfcLoadingIndicator.stopAnimating()
            
            // 动画完成后显示工具栏
            UIView.animate(withDuration: 0.2) {
                self.qfcToolbar.alpha = 1
                self.qfcCloseButton.alpha = 1
                self.qfcPageControl.alpha = 1
            }
        }
    }
    
    private func qfcPerformDismissAnimation(toFrame: CGRect) {
        // 重置任何可能的变换
        qfcImageView.transform = .identity
        
        // 隐藏工具栏
        UIView.animate(withDuration: 0.2, animations: {
            self.qfcToolbar.alpha = 0
            self.qfcCloseButton.alpha = 0
            self.qfcPageControl.alpha = 0
        }) { _ in
            // 执行缩小动画，使用弹簧动画效果
            UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseInOut], animations: {
                self.view.backgroundColor = UIColor.clear
                self.qfcBackgroundView.effect = nil
                self.qfcBackgroundView.alpha = 0
                self.qfcImageView.frame = toFrame
                self.qfcImageView.contentMode = .scaleAspectFill
            }) { _ in
                self.dismiss(animated: false)
            }
        }
    }
}

// MARK: - UIScrollViewDelegate
extension FCCImagePreviewViewController: UIScrollViewDelegate {
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return qfcImageView
    }
    
    func scrollViewDidZoom(_ scrollView: UIScrollView) {
        qfcCenterImageView()
    }
    
    private func qfcCenterImageView() {
        let qfcBoundsSize = qfcScrollView.bounds.size
        var qfcFrameToCenter = qfcImageView.frame
        
        if qfcFrameToCenter.size.width < qfcBoundsSize.width {
            qfcFrameToCenter.origin.x = (qfcBoundsSize.width - qfcFrameToCenter.size.width) / 2
        } else {
            qfcFrameToCenter.origin.x = 0
        }
        
        if qfcFrameToCenter.size.height < qfcBoundsSize.height {
            qfcFrameToCenter.origin.y = (qfcBoundsSize.height - qfcFrameToCenter.size.height) / 2
        } else {
            qfcFrameToCenter.origin.y = 0
        }
        
        qfcImageView.frame = qfcFrameToCenter
    }
}